require( '$d/css/common.less' );
require( './style.less' );
define( [
  'require',
  'jquery',
  'header',
  'bootstrap',
  'selector',
  'bootstrap',
  'cityData',
  'clipboard',
  'indusCategory',
  'message',
  'nav',
  './factory',
  'bigwe_component',
  'unauthor',
  'constants',
  'api',
], function( require, $ ) {
  var cityData = require( 'cityData' ).cityData,
    Clipboard = require( 'clipboard' ),
    fieldCode = require( 'indusCategory' ),
    ShowTitleMessage = require( 'message' ),
    bc = require( 'bigwe_component' ),
    apis = require( 'api' ),
    showTime = ShowTitleMessage.showTime;
  var bwAuthor = require( 'unauthor' );
  var c = require( 'constants' );
  //手机号验证
  var re = /^1[3,4,5,7,8]{1}[0-9]{9}$/;
  //验证码验证
  var codeRe = /^[0-9]{6}$/;
  //邮箱验证
  var emailRe = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  //判断地址栏参数
  if ( GetUrlString( 'from' ) != null || GetUrlString( '_ap_cation' ) != null ) {
    if ( GetUrlString( 'from' ) == 'ACTIVE_MYACCOUNT_BY_URL' && GetUrlString( '_mc_cation' ) == 'updateActive' ) {
      $.ajax( {
        cache: true,
        type: "POST", //用POST方式传输
        dataType: 'text',
        url: apis.MY_ACCOUNT.RegisterPage, //目标地址
        data: {
          email_code: GetUrlString( 'ud' )
        },
        error: function() {
          alert( '链接不存在' );
        },
        success: function( msg ) {
          if ( msg == 'error' ) {
            window.location.href = 'RegisterPage/email_invalid.html';
          } else {
            var new_email = msg;
            $.post( '../my_account/user_update', {
              new_email: new_email,
              done: "new_email"
            }, function( data ) {
              var jsonObj = eval( '(' + data + ')' );
              if ( jsonObj.status == 'success' ) {
                window.location.href = 'my_account';

              }
            } )
          }
        }
      } );
    } else {
      alert( '非法链接' );
      window.location = 'index.html';
    }
  }
  //判断地址栏参数
  if ( GetUrlString( 'new_app_id' ) != null ) {
    $.ajax( {
      type: 'post',
      url: apis.MY_ACCOUNT.GET_FOLLOWERS,
      timeout: 1000,
      data: {
        app_id: GetUrlString( 'new_app_id' )
      },
      complete: function( argument ) {
        ShowTitleMessage.show( '拉取公众号用户数据中', 2500 );
      }
    } )
  }


  var ua = 'from=ACTIVE_MYACCOUNT_BY_URL&_mc_cation=updateActive';
  if ( document.referrer.indexOf( ua ) >= 0 ) {
    alert( '修改成功！' )
  }


  if ( $( '.error_prompt' ).val() == 'true' ) {
    ShowTitleMessage.showWarning( '授权失败，该授权账号不是头条号' );
  }
  $( '[data-toggle="tooltip"]' ).tooltip();
  $( '#mail_edit' ).hide();
  $( '#phone_edit' ).hide();
  $.ajax( {
    type: "POST",
    url: apis.MY_ACCOUNT.GET_USER_INFO,
    success: function( data ) {
      var jsonObj = eval( '(' + data + ')' );
      $( '#user_login' ).html( jsonObj.user_login );
      $( '#nickname' ).html( jsonObj.user_nicename );
      $( '#phone' ).html( jsonObj.user_mobilephone );
      $( '#user_email' ).html( jsonObj.user_email );
      $( '#account_domain' ).html( jsonObj.user_industry );
      $( '#score_count' ).text( jsonObj.user_score );

      if ( !jsonObj.user_login ) {
        $( '#user_login' ).html( '暂无' );
      }
      if ( !jsonObj.user_nicename ) {
        $( '#nickname' ).html( '暂无' );
      }
      if ( !jsonObj.user_mobilephone ) {
        $( '#phone' ).html( '暂无' );
        $( '#phone_edit' ).show();
      }
      if ( !jsonObj.user_email ) {
        $( '#user_email' ).html( '暂无' );
        $( '#mail_edit' ).show();
      }
      if ( !jsonObj.user_area ) {
        $( '#account_territory' ).html( '暂无' );
        $( '#region_edit' ).hide();
      } else {
        get_area( jsonObj.user_area );
      }
      if ( !jsonObj.user_industry ) {
        $( '#account_domain' ).html( '暂无' );
        // $('#industry_modify').hide();
      }
      $('<img src="'+jsonObj.user_face_image+'"/>').prependTo('.head_portrait');
      // if ( jsonObj.user_face_image || '' ) {
      //   // $( '.head_portrait > img' ).attr( 'src', jsonObj.user_face_image );
      // }

      if ( jsonObj.user_industry != null ) {
        var industryStr = '<font color="black" style="font-weight:bold;">' + jsonObj.user_industry.split( '&nbsp;' )[ 0 ] + '</font>&nbsp;&nbsp;' + jsonObj.user_industry.split( '&nbsp;' )[ 2 ]
      }
      if ( jsonObj.user_industry == '其他' ) {
        $( '.field_choice_content>span' ).html( jsonObj.user_industry );
      } else {
        $( '.field_choice_content>span' ).html( industryStr );
      }


    }
  } )

  for ( var i = 0; i < cityData.length; i++ ) {
    var pro = '<option value="' + cityData[ i ][ 'value' ] + '">' + cityData[ i ][ 'text' ] + '</option>';
    $( '#user_pro' ).append( pro ).selectpicker( 'refresh' );
  }

  $.post( "my_account/get_URL", {}, function( data ) {
    if ( data == 'error' ) {
      return;
    }
    var jsonObj = eval( '(' + data + ')' );
    $( '#pre_auth_code' ).val( jsonObj.pre_auth_code );
    $( '#url' ).val( jsonObj.url );
  } );


  //修改手机按钮
  $( '#phone_edit' ).click( function() {
    if ( $( "#phone" ).text() == '暂无' ) {
      $( "#txt_mobilephone" ).val( '' );
    }
    $( '#mobilephone_warning_msg' ).html( '' );
    $( '#verify_warning_msg > span' ).html( '' );

  } );
  //修改邮箱按钮
  $( '#mail_edit' ).click( function() {
    if ( $( "#user_email" ).text() == '暂无' ) {
      $( "#txt_email" ).val( '' );
    }
    $( '#email_warning_msg' ).html( '' );
  } );
  //修改地域按钮
  $( '#user_pro' ).on( 'change', function() {
    for ( var i = 0; i < cityData.length; i++ ) {
      if ( $( '#user_pro' ).val() == cityData[ i ][ 'value' ] ) {
        $( '#user_city' ).empty().selectpicker( 'refresh' );
        var city = '';
        if ( cityData[ i ][ 'children' ].length == 0 ) {
          $( '#user_city' ).selectpicker( 'hide' ).selectpicker( 'refresh' );
        } else {
          $( '#user_city' ).selectpicker( 'show' ).selectpicker( 'refresh' );
          for ( var j = 0; j < cityData[ i ][ 'children' ].length; j++ ) {
            city += '<option value="' + cityData[ i ][ 'children' ][ j ][ 'value' ] + '">' + cityData[ i ][ 'children' ][ j ][ 'text' ] + '</option>';
          }
          $( '#user_city' ).append( city ).selectpicker( 'refresh' );
        }
      }
    }
  } );
  var clipboard = new Clipboard( '#copy_link,#copy_code' );
  clipboard.on( 'success', function( e ) {
    ShowTitleMessage.show( '复制成功！', 1000 );
  } );
  clipboard.on( 'error', function( e ) {
    ShowTitleMessage.show( '您使用的浏览器暂不支持此功能，请手动复制文本框中内容！', 3500 );
  } );
  if ( $( '#invitation_code' ).val() == '' ) {
    $( '#invitation_friends' ).html( '生成邀请码' );
  }
  //邀请好友按钮
  $( '#invitation_friends' ).click( function() {
    if ( $( '#invitation_code' ).val() == '' ) {
      ShowTitleMessage.show( '正在生成！' );
      $.ajax( {
        cache: true,
        type: "POST",
        url: apis.MY_ACCOUNT.CREATE_INVITATION,
        success: function( data ) {
          var data = typeof data === 'string' ? $.parseJSON( data ) : data;
          $( '#invitation_code' ).val( data[ 'code' ] );
          $( '#invitation_link' ).val( data[ 'link' ] );
        },
        complete: function( data ) {
          $( "#check_invitation" ).modal( 'show' );
          ShowTitleMessage.show( '生成成功！', 1000 );
          $( '#invitation_friends' ).html( '邀请好友' )
        }
      } )
    } else {
      $( "#check_invitation" ).modal( 'show' );
    }
  } );
  //行业选择框信息
  var fjid = '';
  //行业选项
  for ( var key in fieldCode ) {
    if ( key.length == 4 ) {
      fjid = key;
      if ( key == '0215' ) {
        var str = '<li class="' + key + '"><span class="field_title_choice">' + fieldCode[ key ] + '</span></li>';
      } else {
        var str = '<li class="' + key + '"><span class="field_title">' + fieldCode[ key ] + '</span></li>';
      }
      $( '.field_choice_option>ul' ).append( str );
    }
    if ( key.length == 6 ) {
      var str = '<span id="' + key + '" class="field_title_choice">' + fieldCode[ key ] + '</span>';
      $( '.' + fjid ).append( str );
    }
  }
  //行业选择框样式
  var hyChoice = 0;
  $( '.field_choice_content' ).click( function() {
    if ( hyChoice == 0 ) {
      $( '.field_choice_option' ).slideDown();
      hyChoice++;
    } else {
      $( '.field_choice_option' ).slideUp();
      hyChoice = 0;
    }
    $( document ).on( "click", function() {
      $( '.field_choice_option' ).slideUp();
      hyChoice = 0;
    } );
  } );
  $( '.field_choice_content' ).click( function( e ) {
    e.stopPropagation();
  } );
  //行业选择框内行业点击事件
  $( '.field_title_choice' ).click( function() {
    $( '.field_title_choice' ).css( 'color', '#9d9d9d' );
    $( this ).css( 'color', 'green' );
    hyChoice = 0;
    $( '.field_choice_option' ).slideUp();
    var parent = $( this ).parent().find( 'span' ).first().html();
    if ( parent == '其他' ) {
      $( '.field_choice_content>span' ).html( '其他' );

      $( '.field_choice_content>span' )[ 0 ].id = '0215';
    } else {
      $( '.field_choice_content>span' ).html( '<font color="black" style="font-weight:bold;">' + parent + '</font>&nbsp;&nbsp;' + $( this ).html() );
      $( '.field_choice_content>span' )[ 0 ].id = $( this )[ 0 ].id;
    }
  } );
  //邮箱登陆跳转链接数组
  var hash = {
    'qq.com': 'http://mail.qq.com',
    'gmail.com': 'http://mail.google.com',
    'sina.com': 'http://mail.sina.com.cn',
    '163.com': 'http://mail.163.com',
    '126.com': 'http://mail.126.com',
    'yeah.net': 'http://www.yeah.net/',
    'sohu.com': 'http://mail.sohu.com/',
    'tom.com': 'http://mail.tom.com/',
    'sogou.com': 'http://mail.sogou.com/',
    '139.com': 'http://mail.10086.cn/',
    'hotmail.com': 'http://www.hotmail.com',
    'live.com': 'http://login.live.com/',
    'live.cn': 'http://login.live.cn/',
    'live.com.cn': 'http://login.live.com.cn',
    '189.com': 'http://webmail16.189.cn/webmail/',
    'yahoo.com.cn': 'http://mail.cn.yahoo.com/',
    'yahoo.cn': 'http://mail.cn.yahoo.com/',
    'eyou.com': 'http://www.eyou.com/',
    '21cn.com': 'http://mail.21cn.com/',
    '188.com': 'http://www.188.com/',
    'foxmail.coom': 'http://www.foxmail.com'
  };
  $( '#edit_nickname' ).on( 'shown.bs.modal', function( e ) {
    $( "#txt_nickname" ).focus();
  } );
  $( '#spa_edit_pn' ).click( function() {
    $( "#edit_nickname" ).modal( 'show' );
    $( "#txt_nickname" ).val( $( "#nickname" ).text() );
  } );
  //修改手机号
  $( "#btn_mobilephone_save" ).click( function() {
    var new_mobilephone = $( "#txt_mobilephone" ).val();
    if ( new_mobilephone == '' || !re.test( new_mobilephone ) ) {
      $( '#mobilephone_warning_msg' ).html( '请输入正确的手机号格式' );
    } else {
      $( '#mobilephone_warning_msg' ).html( '' );
      $.ajax( {
        cache: true,
        type: "POST", //用POST方式传输
        dataType: 'text',
        url: apis.REGISTER.PHONE_VERIFY, //目标地址
        data: {
          user_phone: new_mobilephone
        },
        success: function( msg ) {
          if ( msg == 'success' ) {
            //判断验证码非空
            if ( $( '#verify_input' ).val() != '' && codeRe.test( $( '#verify_input' ).val() ) ) {
              //判断验证码
              $.ajax( {
                cache: true,
                type: "POST", //用POST方式传输
                dataType: 'text',
                url: apis.FORGET_PASSWORD.VERIFY_SMS, //目标地址
                data: {
                  user_phone: new_mobilephone,
                  valid_code: $( '#verify_input' ).val()
                },
                error: function() {
                  alert( '手机号查询失败' );
                },
                success: function( msg ) {
                  msg = eval( '(' + msg + ')' );
                  if ( msg[ 'ret' ] == 0 ) {
                    $.post( '../my_account/user_update', {
                      new_mobilephone: new_mobilephone,
                      done: "new_mobilephone",
                      verify_code: $( '#verify_input' ).val()
                    }, function( data ) {
                      var data = typeof data === 'string' ? $.parseJSON( data ) : data;
                      if ( data.ret == 0 ) {
                        ShowTitleMessage.show( '修改成功！', 1000 );
                      } else {
                        ShowTitleMessage.show( data.msg, 1000 );
                      }
                      $( "#phone" ).html( new_mobilephone );
                      $( "#edit_mobilephone" ).modal( 'hide' );
                      $( "#phone_edit" ).hide();
                    } )
                  } else {
                    $( '#verify_warning_msg > span' ).html( msg[ 'msg' ] );
                  }
                }
              } )
            } else {
              $( '#verify_warning_msg > span' ).html( '请输入正确的验证码' );
            }
          } else {
            $( '#mobilephone_warning_msg' ).show();
            $( '#mobilephone_warning_msg' ).html( '该手机号已注册' );
          }
        }
      } );
    }
  } );
  $( '.get-code' ).click( function() {
    if ( oneClick == 0 ) {
      sendAccountMessage();
    }
  } );
  //修改行业接口
  $( '#btn_field_save' ).click( function() {
    var hyCode = $( '.field_choice_content>span' )[ '0' ].id;
    if ( $( '.field_choice_content>span' ).text() == $( '#account_domain' ).text() ) {
      ShowTitleMessage.showWarning( '行业信息并未做修改', 1000 );
    } else {
      $.post( apis.MY_ACCOUNT.SAVEINDUSTRY, {
        user_industry: hyCode
      }, function( data ) {
        // data = apinput( data );
        var data = typeof data === 'string' ? $.parseJSON(data) : data;
        if ( data == 'ok' ) {
          $( '#account_domain' ).text( $( '.field_choice_content>span' ).text() );
          $( '#industry_modify' ).hide();
          ShowTitleMessage.show( '修改成功！', 1000 );
          $( "#edit_industry" ).modal( 'hide' );
        }
      } )
    }
  } );
  //修改邮箱
  $( "#btn_email_save" ).click( function() {
    $( '#email_warning_msg' ).html( '请输入正确的邮箱格式' );
    $( '#email_warning_msg' ).hide();

    var new_email = $( "#txt_email" ).val();
    if ( new_email == '' || !emailRe.test( new_email ) ) {
      $( '#email_warning_msg' ).show();
    } else {
      $.ajax( {
        cache: true,
        type: "POST", //用POST方式传输
        dataType: 'text',
        url: apis.REGISTER.EMAIL_VERIFY, //目标地址
        data: {
          user_email: new_email
        },
        success: function( msg ) {
          if ( msg == 'success' ) {
            $.ajax( {
              cache: true,
              type: "POST", //用POST方式传输
              dataType: 'text',
              url: apis.MY_ACCOUNT.SEND_MAIL, //目标地址
              data: {
                user_email: new_email,
                user_from: 'my_account'
              },
              error: function() {
                alert( '邮件发送失败' );
              },
              success: function( msg ) {
                if ( msg == 'success' ) {
                  $( '#email_warning_msg' ).hide();
                  if ( window.confirm( '修改申请已提交，请前去邮箱激活' ) ) {
                    var email_log = new_email.split( '@' )[ 1 ];
                    if ( hash[ email_log ] ) {
                      window.open( hash[ email_log ] );
                    } else {
                      alert( "抱歉!未找到对应的邮箱登录地址，请自己登录邮箱查看邮件！" );
                    }
                  }
                  $( "#edit_email" ).modal( 'hide' );
                  $( "#mail_edit" ).hide();
                } else if ( msg == 'email_over' ) {
                  $( '#email_warning_msg' ).show();
                  $( '#email_warning_msg' ).html( '发送次数已达上限' );
                } else if ( msg == 'error_send' ) {
                  $( '#email_warning_msg' ).show();
                  $( '#email_warning_msg' ).html( '邮件发送失败' );
                } else {
                  $( '#email_warning_msg' ).show();
                  $( '#email_warning_msg' ).html( '操作频繁，请稍后在试' );
                }
              }
            } );
          } else {
            $( '#email_warning_msg' ).show();
            $( '#email_warning_msg' ).html( '该邮箱已被注册' );
          }
        }
      } );
    }
  } );
  /**
   * 修改昵称
   */
  $( "#btn_pname_save" ).click( function() {
    var new_name = $( "#txt_nickname" ).val();
    if ( new_name == '' ) {
      $( '#warning_msg' ).show();
    } else {
      $( "#nickname" ).text( $( "#txt_nickname" ).val() );
      $( "#edit_nickname" ).modal( 'hide' );
      $.post( apis.MY_ACCOUNT.USER_UPDATE, {
        new_name: new_name,
        done: "new_name"
      }, function( data ) {
        //data=apinput(data);
        var jsonObj = eval( '(' + data + ')' );
        if ( jsonObj.status == 'success' ) {
          ShowTitleMessage.show( '修改成功！', 1000 );
          $( '.bw_main' ).find( '#user-name-bg' ).html( new_name );
        }
      } )
    }
  } );
  $( ".div-choose-preview input" ).click( function() {
    var type = {};
    type[ 1 ] = '微信号';
    type[ 2 ] = '公众号名称';
    type[ 3 ] = '微信号';
    type[ 4 ] = '公众号名称';
    if ( $( "input[name='rad-watermark']:checked" ).val() != 0 ) {
      watermark = type[ $( "input[name='rad-watermark']:checked" ).val() ];
    }
    $( '.div-img-preview img' ).attr( 'src', 'upload/watermark/get_watermark_img?type=' + $( "input[name='rad-watermark']:checked" ).val() + '&name=' + watermark );
  } );

  // 编辑水印
  $( '#public' ).on( 'click', '.edit_watermark', function() {
    var apid = $( this ).parents( '.gzh_detail' ).attr( 'appid' );
    $( '#watermark_appID' ).val( apid );

    $.post( apis.MY_ACCOUNT.GET_WATERMARK, {
      appid: apid
    }, function( data ) {
      var json = typeof data === 'string' ? $.parseJSON( data ) : data;
      watermark = json.data.watermark_name;
      $( '.div-img-preview img' ).prop( 'src', 'http://www.bigwe.com/upload/watermark/get_watermark_img?type=' + json.data.type_num + '&name=' + watermark );
      $( "input[name='rad-watermark']" ).get( json.data.type_num - 1 ).checked = true;
    } );
  } );
  //保存水印样式
  $( '#watermark' ).find( '#watermark_sure' ).click( function() {
    var type = {};
    type[ 0 ] = '&nbsp;不添加';
    type[ 1 ] = '&nbsp;微信号';
    type[ 2 ] = '&nbsp;使用微信公众号名称';
    type[ 3 ] = '&nbsp;使用微知Logo+微信号';
    type[ 4 ] = '&nbsp;使用微知Logo+微信公众号名称';
    var appid = $( '#watermark_appID' ).val();
    $.post( apis.MY_ACCOUNT.SAVE_WATERMARK_TYPE, {
      save_type: $( "input[name='rad-watermark']:checked" ).val(),
      gzh_appid: appid
    }, function() {
      ShowTitleMessage.show( '修改成功！', 1000 );
    } );
    $( '#watermark' ).modal( 'hide' );
    $( '.account_setting' ).find( '.spa_gray' ).html( type[ $( "input[name='rad-watermark']:checked" ).val() ] );
  } );
  //修改地域
  $( "#btn_area_save" ).click( function() {
    var user_area = '';
    if ( $( '#user_city' ).val() == null ) {
      user_area = $( '#user_pro' ).val();
    } else {
      user_area = $( '#user_city' ).val();
    }
    $.post( apis.MY_ACCOUNT.USER_UPDATE, {
      user_area: user_area,
      done: 'area'
    }, function( data ) {
      var jsonObj = eval( '(' + data + ')' );
      if ( jsonObj.status == 'success' ) {
        var code = jsonObj.data;
        var area = '';
        for ( var i = 0; i < cityData.length; i++ ) {
          if ( code.substr( 0, 4 ) == cityData[ i ][ 'value' ] ) {
            area += cityData[ i ][ 'text' ];

          }
          for ( var j = 0; j < cityData[ i ][ 'children' ].length; j++ ) {
            if ( code == cityData[ i ][ 'children' ][ j ][ 'value' ] ) {
              if ( cityData[ i ][ 'children' ][ j ][ 'text' ] != cityData[ i ][ 'text' ] ) {
                area += '&nbsp;&nbsp;' + cityData[ i ][ 'children' ][ j ][ 'text' ];
              }
            }
          }
        }
        ShowTitleMessage.show( '修改成功！', 1000 );
        $( '#account_territory' ).html( area );
        $( '#account_territory' ).attr( 'title', $( '#account_territory' ).text() );
      } else {
        ShowTitleMessage.showWarning( '修改失败！', 1000 );
      }
      $( "#edit_region" ).modal( 'hide' );
    } )
  } );

  $( ".add_pub" ).click( function() {
    if ( $( '#public' ).find( '.gzh_detail' ).length > 0 ) {
      var url = $( '#url' ).val();
      location.href = url;
    } else {
      location.href = '/hint_accredit';
    }
  } );
  $( '#public' ).on( 'click', '.login-auth', function() {
    var self = $( this );
    app_id = self.parent().attr( 'appid' );
    bwAuthor.authorModify( {
      appid: app_id,
      login_account: self.parent().attr( 'loginaccount' ) || '',
      text: $.trim( self.text() )
    }, function( data ) {
      ShowTitleMessage.show( self.text() + '成功', showTime );
      if ( !self.parent().attr( 'loginaccount' ) ) {
        self.parent().attr( 'loginaccount', data.login_account );
        self.text( '修改授权' );
      }
    } );
  } );
  ! function() {
    var $synchModal = $( '#synch_modal' );
    var editObj = '';
    var type = [ 'mpnews' ];
    $( '#public' ).on( 'click', '.synchro', function() {
      editObj = $( this ).parent();
    } );

    $( '.synch-list input[type="checkbox"]', $synchModal ).change( function() {

      if ( $( this ).val() == 'mpnews' ) {
        if ( type[ 0 ] == 'mpnews' ) {
          type[ 0 ] = '';
        } else {
          type[ 0 ] = 'mpnews';
        }
      }
      if ( $( this ).val() == 'image' ) {
        if ( type[ 1 ] == 'image' ) {
          type[ 1 ] = '';
        } else {
          type[ 1 ] = 'image';
        }
      }
      var checkedLen = $( '.synch-list input[type="checkbox"]:checked' ).length;
      if ( checkedLen ) {
        $( '.ok', $synchModal ).removeAttr( 'disabled' );
      } else {
        $( '.ok', $synchModal ).prop( 'disabled', 'disabled' );
      }
    } );

    /* 确认 */
    $( '.ok', $synchModal ).click( function() {
      if ( !editObj.attr( 'appid' ) ) {
        ShowTitleMessage.showWarning( '无法获取该公众号ID', showTime );
        return;
      }

      $synchModal.modal( 'hide' );
      for ( key in type ) {
        ajaxRequest( editObj, type[ key ] );
      }

    } );

    function ajaxRequest( obj, type ) {
      url = '';
      if ( type == 'mpnews' ) {
        url = apis.MY_ACCOUNT.GET_NEWS_MATERIAL_UNSYNC;
      }
      if ( type == 'image' ) {
        url = apis.MY_ACCOUNT.GET_IMG_MATERIAL_UNSYNC;
      }

      ShowTitleMessage.show( '数据同步中，请注意系统通知', showTime );
      $.ajax( {
        type: 'get',
        url: url,
        timeout: 1000,
        data: {
          app_id: obj.attr( 'appid' )
        },
      } );
    }
  }();


  $( ".submap" ).click( function() {
    var $this = $( this ),
      i = $this.index(),
      len = $( $this.attr( 'href' ) ).children( 'div' ).length;
    $this.addClass( 'bp_active' ).siblings( '.submap' ).removeClass( 'bp_active' );
    if ( i == 1 && len == 0 ) {
      weibo_account();
    } else if ( i == 2 && len == 0 ) {
      toutiao_account();
    }
  } )
  if ( GetUrlString( 'platform' ) == 'sina' ) {
    $( ".submap:eq(1)" ).trigger( "click" );
  } else if ( GetUrlString( 'platform' ) == 'toutiao' ) {
    $( ".submap:eq(2)" ).trigger( "click" );
  }

  //微博新增绑定
  $( "#weibo" ).on( 'click', '.add_weibo', function() {
    var url = $( '#weibo_url' ).val();
    location.href = url;
  } );

  //头条新增绑定
  $( "#toutiao" ).on( 'click', '.add_toutiao', function() {
    var url = $( this ).find( 'input' ).val();
    location.href = url;
  } );
  //微博账号列表
  function weibo_account() {
    $.post( apis.THIRD_PARTY.SINA_ACOUNT_LIST, {}, function( data ) {
      var jsonObj = eval( '(' + data + ')' ),
        weibo_list = '',
        argument = jsonObj.data
      if ( jsonObj.ret != 0 ) {
        $( '#weibo' ).empty().append( '<div class="add_weibo green"><span class="glyphicon glyphicon-plus"></span>新增绑定<input type="hidden" value="/sina/accredit_url" id="weibo_url"></div>' + weibo_list );
      } else {
        for ( var i in argument ) {
          var expire_time = argument[ i ].volid_time;
          var expire_array = expire_time.split( ' ' );
          var curDay = new Date();
          var expire_html = '';
          if ( Date.parse( curDay ) > Date.parse( expire_time ) ) {
            expire_html = '已到期，请' + '<a class="sync_time" href="/sina/accredit_url">重新授权</a>'
          } else {
            expire_html = '到期时间：' + expire_array[ 0 ]
          }
          weibo_list += '<div class="gzh_detail" appid="' + argument[ i ].uid + '">' +
            '<img alt="" src="' + argument[ i ].profile_image_url + '">' +
            '<p class="gzh_type">' +
            '<span class="gzh_name">' + argument[ i ].screen_name + '</span>' +
            '</p>' +
            '<button type="button" class="button_state button_state_green pull-left login-auth">' +
            '<span>更新资料</span>' +
            '</button>' +
            '<p class="pull-left remove_binding">解除绑定</p>' +
            '<p class="weibo_expire">' + expire_html + '</p>' +
            '</div>'
        }

        $( '#weibo' ).empty().append( '<div class="add_weibo green"><span class="glyphicon glyphicon-plus"></span>新增绑定<input type="hidden" value="/sina/accredit_url" id="weibo_url"></div>' + weibo_list );
      }
    } );
  }
  //头条账号列表
  function toutiao_account() {
    $.post( apis.THIRD_PARTY.TOUTIAO_ACOUNT_LIST, {}, function( data ) {
      var jsonObj = typeof data === 'string' ? $.parseJSON( data ) : data,
        toutiao_list = '';
      if ( jsonObj.data ) {
        for ( i in jsonObj.data ) {
          var acount = jsonObj.data[ i ];
          toutiao_list += '<div class="gzh_detail" appid="' + acount.uid + '">' +
            '' + c.surpportHostName + '<img alt="" src="/timthumb.php?w=50&src=">' + acount.avatar_url + '' +
            '<p class="gzh_type">' +
            '<span class="gzh_name">' + acount.screen_name + '</span>' +
            '</p>' +
            // '<p class="pull-left">解除绑定</p>' +
            '</div>'
        }
      }
      $( '#toutiao' ).find( 'add_toutiao' ).remove();
      $( '#toutiao' ).append( '<div class="add_toutiao green"><span class="glyphicon glyphicon-plus"></span>新增绑定<input type="hidden" value="/toutiao/toutiao_authorize"></div>' + toutiao_list );
    } );
  }

  //微博更新用户信息
  function update( targetid, operate_obj ) {
    var toolTipObj = $( '.button_state_green', operate_obj )
      .addClass( 'rotationAnimate' )
      .prop( 'title', '更新中' )
      .tooltip( {
        'trigger': 'manual'
      } )
      .tooltip( 'show' );
    $.ajax( {
      type: 'post',
      dataType: 'json',
      url: apis.MY_ACCOUNT.UPDATE_USER_INFO,
      data: {
        uid: targetid
      },
      success: function( data ) {
        //data = apinput(data);
        ShowTitleMessage.show( '更新成功！', 1000 );
      },
      complete: function() {
        toolTipObj.removeClass( 'rotationAnimate' );
        weibo_account();
      }
    } );
  }
  $( '#weibo' ).on( 'click', '.gzh_detail .button_state', function() {
    var targetid = $( this ).parents( '.gzh_detail' ).attr( 'appid' );
    update( targetid, $( this ) );
  } );
  //微博取消授权
  function cancel( targetid ) {
    $.ajax( {
      type: 'post',
      dataType: 'json',
      url: apis.MY_ACCOUNT.REVOKE_OAUTH2,
      data: {
        uid: targetid
      },
      complete: function() {
        weibo_account();
      }
    } );
  }
  $( '#weibo' ).on( 'click', '.gzh_detail .remove_binding', function() {
    bc.deleteConfirmShowBottom( {
      obj: this,
      text: '确认要取消绑定吗？',
      fun: function() {
        var targetid = $( this ).parents( '.gzh_detail' ).attr( 'appid' );
        cancel( targetid );
      }
    } );
  } );
  //设置
  $( document ).on( 'mouseenter', '.account_set', function( e ) {
    $( this ).find( '.set_tip' ).stop( true, true ).fadeIn();
  } );
  $( document ).on( 'mouseleave', '.account_set', function( e ) {
    $( this ).find( '.set_tip' ).stop( true, true ).fadeOut();
  } );

  //引导绑定弹窗
  var bind_path = window.location.search;
  if ( sessionStorage.account_bind == 1 && bind_path == "?account_bind" ) {
    setTimeout( function() {
      var $body = ( window.opera ) ? ( document.compatMode == "CSS1Compat" ? $( 'html' ) : $( 'body' ) ) : $( 'html,body' ); //operaFix
      $body.scrollTop( 280 );
      $( '.guide_dwrap' ).fadeIn();
      $( '.account_bind' ).fadeIn( function() {
        sessionStorage.account_bind = 0;
      } );
      $( 'body' ).css( 'overflow', 'hidden' );
    }, 1000 );
  }
  if ( sessionStorage.my_account == 1 ) {
    setTimeout( function() {
      var $body = ( window.opera ) ? ( document.compatMode == "CSS1Compat" ? $( 'html' ) : $( 'body' ) ) : $( 'html,body' ); //operaFix
      $body.scrollTop( 280 );
      $( '.guide_dwrap' ).fadeIn();
      $( '.account_zhangh' ).fadeIn( function() {
        sessionStorage.my_account = 0;
      } );
      $( 'body' ).css( 'overflow', 'hidden' );
    }, 1000 );
  }

  if ( bind_path == "?guide_template=1" && $( '.gzh_detail' ).length ) {
    setTimeout( function() {
      var $body = ( window.opera ) ? ( document.compatMode == "CSS1Compat" ? $( 'html' ) : $( 'body' ) ) : $( 'html,body' ); //operaFix

      $body.scrollTop( 89 );
      $( '.guide_dwrap' ).fadeIn();
      $( '#public > .gzh_detail' ).eq( 0 ).find( '.set_tip' ).fadeIn();
      $( '.account_mould' ).fadeIn();

      document.body.parentNode.style.overflowY = "hidden";
      $( 'body' ).css( {
        paddingRight: '17px'
      } );
    }, 1000 );
  }
  $( '.guide_dwrap>div .caoz a:last-child' ).click( function() {
    $( '.guide_dwrap' ).hide();
    $( '.guide_dwrap>div' ).hide();
    $( 'body' ).css( 'overflow', '' );
    $( '#public > .gzh_detail' ).eq( 0 ).find( '.set_tip' ).fadeOut();

    document.body.parentNode.style.overflowY = "auto";
    $( 'body' ).removeAttr( 'style' );
  } );

  //根据地域编码获得地域名称
  function get_area( code ) {
    var str = '';
    for ( var i = 0; i < cityData.length; i++ ) {
      if ( code.substr( 0, 4 ) == cityData[ i ][ 'value' ] ) {
        str = cityData[ i ][ 'text' ];
      }
      for ( var j = 0; j < cityData[ i ][ 'children' ].length; j++ ) {
        if ( code == cityData[ i ][ 'children' ][ j ][ 'value' ] ) {

          if ( cityData[ i ][ 'children' ][ j ][ 'text' ] != cityData[ i ][ 'text' ] ) {
            str += '&nbsp;&nbsp;' + cityData[ i ][ 'children' ][ j ][ 'text' ];
          }
        }
      }
      $( '#account_territory' ).html( str );
      $( '#account_territory' ).attr( 'title', $( '#account_territory' ).text() );
    }
    $( '#user_pro' ).selectpicker( 'val', code.substr( 0, 4 ) );
    for ( var i = 0; i < cityData.length; i++ ) {
      if ( code.substr( 0, 4 ) == cityData[ i ][ 'value' ] ) {
        $( '#user_city' ).empty().selectpicker( 'refresh' );
        var city = '';
        for ( var j = 0; j < cityData[ i ][ 'children' ].length; j++ ) {
          city += '<option value="' + cityData[ i ][ 'children' ][ j ][ 'value' ] + '">' + cityData[ i ][ 'children' ][ j ][ 'text' ] + '</option>';
        }
        $( '#user_city' ).append( city ).selectpicker( 'refresh' );
      }
    }
    $( '#user_city' ).selectpicker( 'val', code );
    if ( code.length == 4 ) {
      $( '#user_city' ).selectpicker( 'hide' )
    }
  }


  var oneClick = 0;
  //验证码发送
  var InterValObj; //timer变量，控制时间
  var count = 60; //间隔函数，1秒执行
  var curCount; //当前剩余秒数
  function sendAccountMessage() {
    if ( re.test( $( '#txt_mobilephone' ).val() ) ) {
      //设置button效果，开始计时
      $.ajax( {
        cache: true,
        type: "POST", //用POST方式传输
        dataType: "text", //数据格式
        url: apis.REGISTER.PHONE_VERIFY, //目标地址
        data: {
          user_phone: $( '#txt_mobilephone' ).val()
        },
        success: function( msg ) {
          if ( msg == 'success' ) {
            //向后台发送处理数据
            $.ajax( {
              cache: true,
              type: "POST", //用POST方式传输
              dataType: "text", //数据格式
              url: apis.REGISTER.SEND_MESSAGE, //目标地址
              data: {
                phone: $( '#txt_mobilephone' ).val(),
                page: 'update'
              },
              error: function( msg ) {
                alert( '发送失败' );
              },
              success: function( data ) {
                var data = typeof data === 'string' ? $.parseJSON( data ) : data;
                ShowTitleMessage.showWarning( data.msg, showTime );
                switch ( data.ret ) {
                  case 41003:
                    //今日短信验证码条数已用完
                    oneClick = 0;
                    $( ".get-code" ).attr( "disabled", "disabled" );
                    break;
                  case 41004:
                    //短信发送失败
                    oneClick = 1;
                    curCount = count;
                    $( ".get-code" ).text( curCount + "s后重新获取" );
                    InterValObj = window.setInterval( AccSetRemainTime, 1000 );
                    break;
                  case 0:
                    //发送成功
                    oneClick = 1;
                    curCount = count;
                    $( ".get-code" ).text( curCount + "s后重新获取" );
                    InterValObj = window.setInterval( AccSetRemainTime, 1000 );
                    break;
                  case 41006:
                    //该手机号已被注册
                    oneClick = 1;
                    curCount = count;
                    $( ".get-code" ).text( curCount + "s后重新获取" );
                    InterValObj = window.setInterval( AccSetRemainTime, 1000 );
                    break;
                  default:
                    //操作频繁，请稍后在试
                    oneClick = 1;
                    curCount = msg;
                    $( ".get-code" ).text( msg + "s后重新获取" );
                    InterValObj = window.setInterval( AccSetRemainTime, 1000 );
                    $( ".get-code" ).attr( "disabled", "disabled" );
                    break;
                }
              }
            } );
          } else {
            $( '#mobilephone_warning_msg' ).html( '该手机号已注册' );
          }
        }
      } );
    } else {
      $( '#mobilephone_warning_msg' ).html( '请输入正确的手机号格式' );
    }

  }

  $( '#edit_mobilephone' ).on( 'hide.bs.modal', function() {
    $( ".get-code" ).removeAttr( "disabled" );
    $( "#verify_input" ).val( "" );
  } );

  //timer处理函数
  function AccSetRemainTime() {
    if ( curCount == 0 ) {
      oneClick = 0;
      window.clearInterval( InterValObj ); //停止计时器
      $( ".get-code" ).text( "重新获取验证码" );
    } else {
      curCount--;
      $( ".get-code" ).text( curCount + "s后重新获取" );
    }
  }
  //获取地址栏参数

  function GetUrlString( name ) {
    var reg = new RegExp( "(^|&)" + name + "=([^&]*)(&|$)" );
    var r = window.location.search.substr( 1 ).match( reg );
    if ( r != null ) return unescape( r[ 2 ] );
    return null;
  }

  //校验密码：只能输入6-20个字母、数字、下划线  
  function isPasswd( s ) {
    var patrn = /^(\w){6,20}$/;
    if ( !patrn.exec( s ) ) return false
    return true
  }
  // 修改密码
  $( '#edit_password' ).on( 'show.bs.modal', function() {
    $( '#edit_password' ).find( '.pwd_text' ).val( '' ).data( 'format', false ).attr( 'data-format', false ).removeClass( 'error' );
    $( '#edit_password' ).find( '#old_msg,#new_msg,#new_msg2' ).text( '' ).parent().addClass( 'hide' );
  } )
  $( '#edit_password' ).on( 'blur', '#old_pswd', function() {
    if ( $( this ).val() != '' ) {
      if ( !isPasswd( $( this ).val() ) ) {
        $( '#old_msg' ).text( '密码格式错误，建议使用6-20个字母、数字、下划线' ).parent().removeClass( 'hide' );
        $( this ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
      } else {
        $( '#old_msg' ).text( '' ).parent().addClass( 'hide' );
        $( this ).removeClass( 'error' ).data( 'format', true ).attr( 'data-format', true );
      }
    }
  } );
  $( '#edit_password' ).on( 'blur', '#pswd', function() {
    if ( $( this ).val() != '' ) {
      if ( $( this ).val().length < 6 ) {
        $( '#new_msg' ).text( '新密码不能低于6位' ).parent().removeClass( 'hide' );
        $( this ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
      } else if ( $( this ).val().length > 20 ) {
        $( '#new_msg' ).text( '新密码不能多于20位' ).parent().removeClass( 'hide' );
        $( this ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
      } else if ( !isPasswd( $( this ).val() ) ) {
        $( '#new_msg' ).text( '建议使用字母、数字和符号两种及以上的组合，6-20个字符' ).parent().removeClass( 'hide' );
        $( this ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
      } else {
        $( '#new_msg' ).text( '' ).parent().addClass( 'hide' );
        $( this ).removeClass( 'error' ).data( 'format', true ).attr( 'data-format', true );
      }
      if ( $( '#pwd_repeat' ).val() != '' ) {
        if ( $( '#pwd_repeat' ).val() != $( this ).val() ) {
          $( '#new_msg2' ).text( '两次密码输入不一致' ).parent().removeClass( 'hide' );
          $( '#pwd_repeat' ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
        } else {
          $( '#new_msg2' ).text( '' ).parent().addClass( 'hide' );
          $( '#pwd_repeat' ).removeClass( 'error' ).data( 'format', true ).attr( 'data-format', true );
        }
      }
    }
  } );
  $( '#edit_password' ).on( 'blur', '#pwd_repeat', function() {
    if ( $( this ).val() != '' ) {
      if ( $( this ).val() != $( '#pswd' ).val() ) {
        $( '#new_msg2' ).text( '两次密码输入不一致' ).parent().removeClass( 'hide' );
        $( this ).addClass( 'error' ).data( 'format', false ).attr( 'data-format', false );
      } else {
        $( '#new_msg2' ).text( '' ).parent().addClass( 'hide' );
        $( this ).removeClass( 'error' ).data( 'format', true ).attr( 'data-format', true );
      }
    }
  } );
  $( "#btn_pwd_save" ).click( function() {
    var user_login = $( '#user_login' ).text();
    var old_pwd = $( "#old_pswd" );
    var new_pwd = $( '#pswd' );
    var pwd_repeat = $( '#pwd_repeat' );
    if ( !old_pwd.data( 'format' ) ) {
      if ( old_pwd.val() == '' ) {
        $( '#old_msg' ).text( '原密码不能为空' ).parent().removeClass( 'hide' );
      }
      old_pwd.addClass( 'error' ).focus();
      return;
    } else if ( !new_pwd.data( 'format' ) ) {
      if ( new_pwd.val() == '' ) {
        $( '#new_msg' ).text( '新密码不能为空' ).parent().removeClass( 'hide' );
      }
      new_pwd.addClass( 'error' ).focus();
      return;
    } else if ( !pwd_repeat.data( 'format' ) ) {
      if ( pwd_repeat.val() == '' ) {
        $( '#new_msg2' ).text( '请再次输入密码' ).parent().removeClass( 'hide' );
      } else if ( new_pwd.val() != pwd_repeat.val() ) {
        $( '#new_msg2' ).text( '两次密码输入不一致' ).parent().removeClass( 'hide' );
      }
      pwd_repeat.addClass( 'error' ).focus();
      return;
    }
    $.post( apis.MY_ACCOUNT.USER_UPDATE, {
      user_login: user_login,
      old_pwd: old_pwd.val(),
      new_pwd: new_pwd.val(),
      done: 'pwd'
    }, function( data ) {
      var data = typeof data === 'string' ? $.parseJSON( data ) : data;
      if ( data.ret == 0 ) {
        ShowTitleMessage.show( '修改成功！', 1000 );
        $( "#edit_password" ).modal( 'hide' );
      } else {
        $( '#old_msg' ).text( data.msg ).parent().removeClass( 'hide' );
      }
    } )
  } );
} )